package sy.dao.base.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import sy.dao.base.BaseDaoI;

@Repository("baseDao")
public class BaseDaoImpl<T extends Serializable, PK extends Serializable> implements BaseDaoI<T, PK> {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 注入hibernate的sessionFactory
	 */
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	/**
	 * 获得当前事物的session
	 * 
	 * @return org.hibernate.Session
	 */
	public Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

	@Override
	public T get(Class<T> clazz, PK pk) {
		return (T) this.getCurrentSession().get(clazz, pk);
	}

	@Override
	public T save(T o) {
		return (T) this.getCurrentSession().save(o);
	}

	@Override
	public T update(T o) {
		this.getCurrentSession().update(o);
		return o;
	}

	@Override
	public T saveOrUpdate(T o) {
		this.getCurrentSession().saveOrUpdate(o);
		return o;
	}

	@Override
	public void delete(T o) {
		this.getCurrentSession().delete(o);
	}

	@Override
	public T find(String hql) {
		return this.find(hql, null);
	}

	@Override
	public T find(String hql, Map<String, Object> params) {
		List<T> list = this.findAll(hql, params, 1, 1);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<T> findAll(String hql) {
		return this.findAll(hql, null);
	}

	@Override
	public List<T> findAll(String hql, Map<String, Object> params) {
		return this.findAll(hql, params, null, null);
	}

	@Override
	public List<T> findAll(String hql, Integer page, Integer rows) {
		return this.findAll(hql, null, page, rows);
	}

	@Override
	public List<T> findAll(String hql, Map<String, Object> params, Integer page, Integer rows) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				q.setParameter(key, params.get(key));
			}
		}
		if (page != null && rows != null) {
			q.setFirstResult((page - 1) * rows).setMaxResults(rows);
		}
		return q.list();
	}

	@Override
	public Long total(String hql) {
		return this.total(hql, null);
	}

	@Override
	public Long total(String hql, Map<String, Object> params) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				q.setParameter(key, params.get(key));
			}
		}
		return (Long) q.uniqueResult();
	}

}
